<?php

namespace Frieza\Modules\Activity\Controllers;

use App\Admin\Extensions\Column\LinkSelect;
use App\Admin\Extensions\Tools\PreviewButton;
use App\Admin\Extensions\Tools\UserButton;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\activity\Page as mPage;
use Biz\model\activity\PageModule;
use Biz\model\activity\PageModule as mPageModule;
use Biz\model\activity\PageModuleArticle as mPageModuleArticle;
use Biz\model\activity\PageModuleGoods as mPageModuleGoods;
use Biz\model\activity\PageModuleH5Obj as mPageModuleH5Obj;
use Biz\model\activity\PageModuleImg as mPageModuleImg;
use Biz\model\activity\PageModuleWiki as mPageModuleWiki;
use Biz\service\activity\ActivityPage;
use Biz\service\activity\Page;
use Biz\service\activity\Page as sPage;
use Biz\tools\BizUrl;
use Doraemon\model\Article as mArticle;
use Doraemon\model\Guide;
use Doraemon\model\Member;
use Doraemon\model\Topic\TopicActivity;
use Doraemon\model\TopicTab;
use Doraemon\pockets\constInterface\LinkConf;
use Doraemon\service\Blank;
use Doraemon\service\Content\AdmContent;
use Doraemon\service\TopicTab as sTopicTab;
use Doraemon\service\User;
use Doraemon\tools\BlockType;
use Doraemon\tools\BlockTypeMapping;
use Doraemon\tools\IdParse;
use Doraemon\tools\Log as tLog;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class PageController extends Controller
{

    public function pageList(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", 10);
        $page = $request->input("page", 1);
        $limit = [
            ($page - 1) * $pageSize,
            $pageSize
        ];

        $condition = [];
        $requestParams = $request->all();
        if (isset($requestParams['unique_id']) && $requestParams['unique_id'] > 0) {
            $condition['id'] = $requestParams['unique_id'];
        }
        if (isset($requestParams['app_status']) && $requestParams['app_status'] > 0) {
            $condition['app_status'] = $requestParams['app_status'];
        }
        if (isset($requestParams['mini_status']) && $requestParams['mini_status'] > 0) {
            $condition['mini_status'] = $requestParams['mini_status'];
        }
        if (isset($requestParams['title']) && strlen(trim($requestParams['title']))) {
            $condition['title[~]'] = trim($requestParams['title']);
        }
        if (isset($requestParams['page_type']) && $requestParams['page_type'] > 0) {
            $condition['page_type'] = $requestParams['page_type'];
        }
        if (isset($requestParams['status']) && $requestParams['status'] > 0) {
            $condition['status'] = $requestParams['status'];
        } else {
            $condition['status'] = [
                mPage::STATUS_NORMAL,
                mPage::STATUS_OFFLINE
            ];
        }

        $content
            ->header('活动页列表')
            ->description(' ');

        $listAndTotal = mPage::getListAndTotal(['AND' => $condition], $limit);
        $gridModel = new pGridDataModel($listAndTotal['list'], $listAndTotal['total'], [
            'perPage' => $pageSize
        ]);

        $listGrid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function ($filter) {

                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('unique_id', '活动页ID');
                        $filter->equal('title', '活动名称');
                    });

                    $statusSelect = [
                        mPage::STATUS_NORMAL => '展示',
                        mPage::STATUS_OFFLINE => '隐藏',
                    ];
                    $filter->column(1 / 3, function ($filter) use ($statusSelect) {
                        $filter->equal('page_type', '页面类型')->select(mPage::PAGE_TYPE_DESC);
                        $filter->equal('status', '展示状态')->select($statusSelect);

                    });
                    $filter->column(1 / 3, function ($filter) use ($statusSelect) {
                        $filter->equal('app_status', 'App-推荐')->select($statusSelect);
                        $filter->equal('mini_status', '商城小程序')->select($statusSelect);

                    });
                    $filter->expand();
                });
                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                //添加按钮
                $grid->tools(function (Grid\Tools $tool) {
                    $tool->append(new UserButton(UserButton::TYPE_HREF, 'add', '添加活动'));
                });
                $grid->column('id', '活动ID');
                $grid->column('title', '活动名称');
                $grid->column('tags_array', '标签')->label();
                $grid->column('url', '活动页地址')->urlWrapper();
                $grid->column('start_time', '开始时间');
                $grid->column('end_time', '结束时间');
                $status = [
                    'on' => [
                        'value' => mPage::STATUS_NORMAL,
                        'text' => '展示'
                    ],
                    'off' => [
                        'value' => mPage::STATUS_OFFLINE,
                        'text' => '隐藏'
                    ],
                ];
                $grid->column('app_status', 'App-推荐')->switchToggle($status);
                $grid->column('mini_status', '商城小程序')->switchToggle($status);
                $grid->column('status', '展示状态')->switchToggle($status);
                $grid->column('page_type', '页面类型')->display(function ($page_type) {
                    return mPage::PAGE_TYPE_DESC[$page_type];
                });;
            });
        $content->row($listGrid);
        return $content;
    }

    public function moduleCopy(Content $content, $moduleId = 0)
    {
        $moduleInfo = mPageModule::getModuleInfoByModuleId($moduleId);
        $moduleName = isset($moduleInfo['title']) ? $moduleInfo['title'] : '';
        return view('activity::page.module_copy', [
            'moduleId' => $moduleId,
            'moduleName' => $moduleName,
        ]);
    }

    public function moduleCopySave(Request $request)
    {
        $requestInfo = $request->all([
            'moduleId',
            'pageId'
        ]);
        $pageId = trim($requestInfo['pageId']);
        $moduleId = trim($requestInfo['moduleId']);
        $message = '操作成功';
        $status = true;
        $moduleImages = [];
        $moduleGoods = [];
        $moduleWiki = [];
        try {
            $moduleInfo = mPageModule::getModuleInfoByModuleId($moduleId);
            if (!$moduleInfo) {
                throw new \Exception('模块不存在');
            }
            if ($moduleInfo['page_id'] == $pageId) {
                throw new \Exception('不能复用至当前活动');
            }
            switch ($moduleInfo['type']) {
                case mPageModule::MODULE_TYPE_IMG:
                    $moduleImages = mPageModuleImg::getImgByModuleId($moduleInfo['id']);
                    break;
                case mPageModule::MODULE_TYPE_GOODS:
                    $moduleGoods = mPageModuleGoods::getGoodsByModuleId($moduleInfo['id']);
                    break;
                case mPageModule::MODULE_TYPE_WIKI:
                    $moduleWiki = mPageModuleWiki::getWikiByModuleId($moduleInfo['id']);
            }
            mPageModule::action(function () use ($moduleInfo, $pageId, $moduleImages, $moduleGoods, $moduleWiki) {
                //复制模块信息
                $moduleInfo['page_id'] = $pageId;
                unset($moduleInfo['id']);
                $newModuleId = mPageModule::saveModule($moduleInfo);
                if (!$newModuleId) {
                    throw new \Exception('复制模块信息失败');
                }

                //复制图片模块
                if ($moduleImages) {
                    foreach ($moduleImages as $image) {
                        $addData = [
                            'page_id' => $pageId,
                            'module_id' => $newModuleId,
                            'pic_id' => $image['pic_id'],
                            'link_type' => $image['link_type'],
                            'link_params' => $image['link_params'],
                            'link_url' => $image['link_url'],
                            'out_link' => $image['out_link'],
                            'sort' => $image['sort'],
                        ];
                        $rs = mPageModuleImg::insertModuleImg($addData);
                        if (!$rs) {
                            throw new \Exception('复制图片模块失败');
                        }
                    }
                }

                //复制商品模块
                if ($moduleGoods) {
                    foreach ($moduleGoods as $good) {
                        $addData = [
                            'page_id' => $pageId,
                            'module_id' => $newModuleId,
                            'goods_id' => $good['goods_id'],
                            'goods_desc' => $good['goods_desc'],
                            'goods_price' => $good['goods_price'],
                            'sort' => $good['sort'],
                        ];
                        $rs = mPageModuleGoods::insertModuleGoods($addData);
                        if (!$rs) {
                            throw new \Exception('复制商品模块失败');
                        }
                    }
                }
                //复制Wiki模块
                if ($moduleWiki) {
                    foreach ($moduleWiki as $wiki) {
                        $addData = [
                            'page_id' => $pageId,
                            'module_id' => $newModuleId,
                            'wiki_id' => $wiki['wiki_id'],
                            'wiki_desc' => $wiki['wiki_desc'],
                            'wiki_price' => $wiki['wiki_price'],
                            'sort' => $wiki['sort'],
                        ];
                        $rs = mPageModuleWiki::insertModuleWiki($addData);
                        if (!$rs) {
                            throw new \Exception('复制商品模块失败');
                        }
                    }
                }
            });


        } catch (\Exception $e) {
            $status = false;
            $message = "操作失败,信息:" . $e->getMessage();
        }
        return response()->json(compact('moduleImages', 'moduleGoods', 'moduleWiki', 'status', 'message', 'moduleInfo'));
    }

    public function pageEdit(Content $content, $id = 0)
    {
        $tab = new Tab();
        //基础信息
        $baseInfoForm = $this->_getPageBaseInfoForm($id);
        $tab->add('基础信息', $baseInfoForm);
        if ($id) {
            //模块配置
            $detailGrid = $this->_getPageModuleGrid($id);
            $tips = "<div class='alert alert-warning'>小程序首页最多配置10个锚点导航条，每个锚点的商品最多20个</div>";

            $tab->add('模块列表', $tips . $detailGrid->render(), true);
        }
        $content->header('活动页配置')
            ->breadcrumb([
                'text' => '活动列表',
                'url' => '/activity/page'
            ], ['text' => '活动页配置'])
            ->row($tab);
        return $content;
    }



    /**
     * 添加模块工具栏配置
     * @param $grid Grid
     * @return string
     */
    private static function _getPageModuleTools($grid)
    {
        $toolsConfig = [
            [
                'type' => mPageModule::MODULE_TYPE_ANCHOR,
                'href' => 'href',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_TAB,
                'href' => '/addTabModule',
            ],
            [
                'type' => -1,
                'link' => 'line',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_GOODS,
                'link' => 'href',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_SPECIAL_GOODS,
                'link' => 'href',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_IMG,
                'link' => 'href',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_WIKI,
                'link' => 'href',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_CARD_BANNER,
                'link' => 'href',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_CARD_ARTICLE,
                'link' => 'href',
            ],
            [
                'type' => -1,
                'link' => 'line',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_FOLLOW,
                'link' => 'href',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_DESIGNER,
                'link' => 'href',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_MULTI_FOLLOW,
                'link' => 'href',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_WATERFALL,
                'link' => 'href',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_CARD_WATERFALL,
                'link' => 'href',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_FLOAT,
                'link' => 'href',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_VIDEO,
                'link' => 'href',
            ],
            [
                'type' => -1,
                'link' => 'line',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_SPECIAL_ARTICLE,
                'link' => 'href',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_SPECIAL_NOTE,
                'link' => 'href',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_GOODS_SET,
                'link' => 'href',
            ],
            [
                'type' => mPageModule::MODULE_TYPE_BLIND_BOX,
                'link' => 'href',
            ],  [
                'type' => mPageModule::MODULE_TYPE_CPL,
                'href' => 'line',
            ], [
                'type' => mPageModule::MODULE_TYPE_SHOP_BOOK,
                'href' => 'line',
            ],

        ];
        return ActivityPage::pageModuleToolbar($grid, $toolsConfig);
    }

    /**
     * @desc 模块列表
     * @param $pageId
     * @return Grid
     */
    private function _getPageModuleGrid($pageId)
    {
        Admin::script($this->reloadScript());
        $moduleList = sPage::admGetModuleList($pageId);
        $gridModel = new pGridDataModel($moduleList);

        $detailGrid = Admin::grid($gridModel,
            function (Grid $grid) use ($pageId) {
                $grid->disableFilter();
                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->option('usePagination', false);
                //添加按钮
                $grid->tools(function (Grid\Tools $tool) use ($pageId, $grid) {
                    $tool->append(self::_getPageModuleTools($grid));
                    $tool->append(new PreviewButton(BizUrl::h5ActivityPage($pageId) . "&preview=1"));

                });

                $grid->column('id')->sort();
                $grid->column('title', '模块名称');
                $grid->column('type', '类型')->display(function ($type) {
                    return mPageModule::MODULE_TYPE_VIEW[$type];
                });
                $grid->column('style', '样式')->display(function ($style) {
                    return mPageModule::MODULE_SYLE_VIEW[$style] ?? "-";
                });
                $grid->column('start_time', '开始时间')->editable('datetime');
                $grid->column('end_time', '结束时间')->editable('datetime');
                $grid->column('anchor', '锚点');
                $grid->column('tab', 'tab锚点');
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    if (in_array($actions->row->type, [
                        mPageModule::MODULE_TYPE_IMG,
                        mPageModule::MODULE_TYPE_GOODS,
                        mPageModule::MODULE_TYPE_WIKI
                    ])) {
                        $actions->append('<a href="javascript:layer.open({
                type: 2,
                title: \'选择复用活动\',
                maxmin: true,
                area: [\'800px\', \'500px\'],
                content: \'/admin/activity/page/' . $actions->row->id . '/copy\'
            });">复用模块</a>');
                    }

                    switch ($actions->row->type) {
                        case mPageModule::MODULE_TYPE_TAB:
                            $actions->disableEdit();
                            break;
                        case mPageModule::MODULE_TYPE_WATERFALL:
                            $ext = json_decode($actions->row->ext);
                            $topic_id = isset($ext->topic_id) ? $ext->topic_id : 0;
                            if ($topic_id) {
                                $actions->append('<a class="fa fa-refresh reloadJoin" data-id="' . $topic_id . '" href="javascript:;">更新参与数</a>');
                            }
                            break;
                    }
                });
            });
        return $detailGrid;
    }

    public function reloadTopic($pageId, $topicId)
    {
        $topicIds = explode(',', $topicId);
        if ($topicIds) {
            foreach ($topicIds as $v) {
                Page::pageModuleTopicCounter($v);
            }
        }
    }

    private function reloadScript()
    {
        return <<<SCRIPT
        $('.reloadJoin').unbind('click').click(function(){
            var id = $(this).data('id');
            let url = id  + '/reload'
            let params = {}
            toastr.success('更新任务已经添加,稍后查看');
            $.post(url, params);
        });
SCRIPT;
    }

    public function savePage(Request $request, $id = 0)
    {
        $pageInfo = $request->all([
            'title',
            'sub_title',
            'page_type',
            'tags',
            'bgcolor',
            'cover_img_big',
            'cover_img_small',
            'icon',
            'share_title',
            'share_desc',
            'share_img',
            'relation_id',
            'start_time',
            'end_time'
        ]);
        $pageInfo['tags'] = implode(",", array_map(function ($tag) {
            return '#' . trim($tag) . '#';
        }, array_filter($pageInfo['tags'])));
        $pageInfo['relation_id'] = implode(",", array_filter($pageInfo['relation_id']));

        try {
            if ($id > 0) {
                $oldInfo = mPage::getPageInfoById($id);
                if (!$oldInfo) {
                    throw new \Exception('修改的活动不存在');
                }

                if ($oldInfo['app_status'] == mPage::STATUS_NORMAL && $pageInfo['cover_img_small'] == '') {
                    throw new \Exception('本活动页展示在App-推荐模块，请上传小封面');
                }
                if ($oldInfo['mini_status'] == mPage::STATUS_NORMAL && $pageInfo['cover_img_big'] == '') {
                    throw new \Exception('本活动页展示在商城小程序，请上传大封面');
                }
            }

            $id = mPage::savePageInfo($pageInfo, $id);
            if (!$id) {
                throw new \Exception('保存失败');
            }
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/activity/page/' . $id . '/edit')->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    /**
     * 修改模块基础信息
     * @param Request $request
     * @param $pageId
     * @param $moduleId
     * @return \Illuminate\Http\RedirectResponse
     */
    public function saveModule(Request $request, $pageId, $moduleId)
    {
        try {
            //所有参数
            $params = $request->all();
            //详见：/g_biz/model/activity/PageModule.php
            $type = $params['type'] ?? 0;
            $title = $params['title'] ?? '';
            $style = $params['style'] ?? 0;
            $anchor = $params['anchor'] ?? '';
            $tab = $params['tab'] ?? '';
            $moduleInfo = [
                'title' => $request->input('title', ''),
                'style' => $request->input('style', 0),
                'anchor' => $request->input('anchor', ''),
                'tab' => $request->input('tab', ''),
                'type' => $type,
            ];

            switch ($type) {
                case mPageModule::MODULE_TYPE_SHOP_BOOK:
                    $pic_id = $params['pic_id'] ?? '';
                    $shop_id = $params['shop_id'] ?? '';
                    $ext = compact('pic_id', 'shop_id');
                    break;
                case mPageModule::MODULE_TYPE_WIKI:
                    $jump = $params['jump'] ?? 1;
                    $ext = compact('jump');
                    break;
                //一键关注
                case mPageModule::MODULE_TYPE_MULTI_FOLLOW:
                    $pic_id = $params['pic_id'] ?? '';
                    $done_pic_id = $params['done_pic_id'] ?? '';
                    if (empty($pic_id)) throw new \Exception('一键关注图必须');
                    if (empty($done_pic_id)) throw new \Exception('已关注图必须');
                    $ext = compact('pic_id', 'done_pic_id');
                    break;
                //关注用户
                case mPageModule::MODULE_TYPE_FOLLOW:
                    $obj = $params['obj'] ?? [];
                    $link_type = $obj['link_type'] ?? '';
                    $link_params = isset($obj['link_params']) ? json_encode($obj['link_params'],
                        JSON_UNESCAPED_UNICODE) : '';
                    //名片底图
                    $card_info['pic_base_id'] = $params['pic_base_id'] ? explode(',', $params['pic_base_id'])[0]: '';
                    //名片背景
                    $card_info['pic_bg_id'] = $params['pic_bg_id'] ? explode(',', $params['pic_bg_id'])[0] : '';
                    //名称颜色 1:黑色 2：白色
                    $card_info['name_color'] = $params['name_color'] ?? 1;
                    //内容颜色 1:黑色 2：白色
                    $card_info['content_color'] = $params['content_color'] ?? 1;
                    $button_color = $request->input("button_color", '');
                    $text_color = $request->input("text_color", '');
                    $ext = [
                        'uid' => $request->input('uid', 0),
                        'link_type' => $link_type,
                        'link_params' => $link_params,
                        'card_info' => $card_info,
                        'button_color' => $button_color,
                        'text_color' => $text_color,
                    ];
                    break;
                case mPageModule::MODULE_TYPE_DESIGNER:
                    $obj = $request->input("obj", []);
                    $link_type = $obj['link_type'] ?? '';
                    $link_params = isset($obj['link_params']) ? json_encode($obj['link_params'], JSON_UNESCAPED_UNICODE) : '';
                    $custom_title = $request->input("custom_title", '');
                    $custom_img = $request->input("custom_img", '');
                    $button_color = $request->input("button_color", '');
                    $text_color = $request->input("text_color", '');
                    $ext = [
                        'uid' => $request->input('uid', 0),
                        'link_type' => $link_type,
                        'link_params' => $link_params,
                        'custom_title' => $custom_title,
                        'custom_img' => $custom_img,
                        'button_color' => $button_color,
                        'text_color' => $text_color,
                    ];
                    break;
                case mPageModule::MODULE_TYPE_ANCHOR:
                    $bg_color = $request->input("bg_color", '');
                    $text_color = $request->input("text_color", '');
                    $ext = compact('bg_color', 'text_color');
                    break;
                case mPageModule::MODULE_TYPE_VIDEO:
                    $pic_id = $request->input('pic_id', '');
                    if (empty($pic_id)) throw new \Exception('没有上传封面');
                    $ext = [
                        'link' => $request->input('link', mPageModule::MODULE_WATERFALL_HIDE_NUM),
                        'pic_id' => $pic_id,
                    ];
                    break;
                case mPageModule::MODULE_TYPE_WATERFALL:
                    $topicIds = $request->input('topic_id', '');
                    $sortType = null;
                    foreach ($topicIds as $topicId) {
                        if ($topicId) {
                            $topicIdData = explode(PageModule::MODULE_WATERFALL_TAB_DELIMITER, $topicId);
                            $topicSort = $topicIdData['1'] > sTopicTab::DEFAULT_TAB_NEW ? sTopicTab::DEFAULT_TAB_HOT : $topicIdData['1'];
                            if ($sortType && $sortType != $topicSort) {
                                throw new \Exception('不能选择不同排序类型的话题Tab');
                            }
                            $sortType = $topicSort;
                        }

                    }
                    $ext = [
                        'is_show_num' => $request->input('is_show_num', mPageModule::MODULE_WATERFALL_HIDE_NUM),
                        'topic_id' => $request->input('topic_id', ''),
                    ];
                    break;
                case mPageModule::MODULE_TYPE_SPECIAL_ARTICLE:
                case mPageModule::MODULE_TYPE_SPECIAL_NOTE:
                    $ext = [
                        'button_color' => $request->input('button_color', ''),
                    ];
                    break;
                case mPageModule::MODULE_TYPE_CARD_ARTICLE:
                    break;
                case mPageModule::MODULE_TYPE_FLOAT:
                    $ext = [
                        'bgcolor' => $request->input('bgcolor', ''),
                        'link_url' => $request->input('link_url', ''),
                        'out_link' => $request->input('out_link', ''),
                        'link_type' => $request->input('link_type', ''),
                        'link_params' => $request->input('link_params', ''),
                    ];
                    break;
                case mPageModule::MODULE_TYPE_GOODS_SET:
                    //wiki_ids
                    $top_wiki_ids = implode(',', array_slice(array_unique(explode(',', $params['top_wiki_ids'])), 0, 6)) ?? "";
//                    $topic_ids = implode(',', array_slice(array_unique(explode(',', $params['topic_ids'])), 0, 6)) ?? "";
                    $topic_ids = (int)$params['topic_ids'] ?: '';
                    $ext = [
                        'top_wiki_ids' => $top_wiki_ids,
                        'topic_ids' => $topic_ids,
                        'bg_img' => $params['bg_img'] ? explode(',', $params['bg_img'])[0] : '',
                    ];
                    break;
                case mPageModule::MODULE_TYPE_BLIND_BOX:
                    $ext = [
                        'bg_img' => $params['bg_img'] ?? '',
                        'btn_before' => $params['btn_before'] ?? '',
                        'btn_after' => $params['btn_after'] ?? '',
                    ];
                    break;
                case mPageModule::MODULE_TYPE_CPL:
                    $ext = [
                        'basic_field' =>[
                             'name' => in_array("name" , $params['basic_field']) ? true : false,
                             'phone' => in_array("phone" , $params['basic_field']) ? true : false,
                             'area' => in_array("area" , $params['basic_field']) ? true : false
                        ],
                        'desc' => $params['desc'] ? : '',
                        'submit_desc' => $params['submit_desc'] ? : '',
                        'is_show_joiner_data' =>  $params['is_show_joiner_data'] ? : 0

                    ];
                    break;
            }
            if (isset($ext)) {
                $moduleInfo['ext'] = json_encode($ext, JSON_UNESCAPED_UNICODE);
            }
            $moduleInfo['page_id'] = $pageId;

            $moduleId = mPageModule::saveModule($moduleInfo, $moduleId);

            if ($moduleId) {
                $success = new MessageBag([
                    'title' => '保存成功'
                ]);
                return redirect('/admin/activity/page/' . $pageId . '/edit/' . $moduleId . '/edit')->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '保存失败' . json_encode(mPageModule::log())
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '失败信息:' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function saveModuleData(Request $request, $pageId, $moduleId)
    {
        $name = $request->input('name');
        $value = $request->input('value');
        $moduleInfo[$name] = $value;
        $moduleId = mPageModule::saveModule($moduleInfo, $moduleId);
        if ($moduleId) {
            return response()->json([
                'status' => true,
                'message' => "修改成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "修改失败",
            ]);
        }
    }


    public function addAnchorModule($pageId)
    {
        $moduleInfo = [
            'title' => "锚点导航条",
            'style' => 1,
            'type' => mPageModule::MODULE_TYPE_ANCHOR,
            'page_id' => $pageId
        ];
        mPageModule::saveModule($moduleInfo);
    }

    public function addTabModule($pageId)
    {
        $moduleInfo = [
            'title' => mPageModule::MODULE_TYPE_VIEW[mPageModule::MODULE_TYPE_TAB],
            'style' => 1,
            'type' => mPageModule::MODULE_TYPE_TAB,
            'page_id' => $pageId
        ];
        mPageModule::saveModule($moduleInfo);
    }

    public function sortModule(Request $request)
    {
        $sortInfo = $request->input('sort');
        mPageModule::saveModuleSort($sortInfo);
    }


    /**
     * 修改排序
     * @param Request $request
     * @param $pageId
     * @param $moduleId
     */
    public function sortModuleItems(Request $request, $pageId, $moduleId)
    {
        $sortInfo = $request->input('sort');
        $moduleInfo = mPageModule::getModuleInfoByModuleId($moduleId);
        switch ($moduleInfo['type']) {
            case mPageModule::MODULE_TYPE_IMG:
                mPageModuleImg::saveModuleImgSort($sortInfo);
                break;
            case mPageModule::MODULE_TYPE_GOODS:
            case mPageModule::MODULE_TYPE_SPECIAL_GOODS:
                mPageModuleGoods::saveModuleGoodsSort($sortInfo);
                break;
            case mPageModule::MODULE_TYPE_WIKI:
                mPageModuleWiki::saveModuleWikiSort($sortInfo);
                break;
            case mPageModule::MODULE_TYPE_CARD_ARTICLE:
            case mPageModule::MODULE_TYPE_CARD_WATERFALL:
                mPageModuleArticle::saveModuleSort($sortInfo);
                break;
            case mPageModule::MODULE_TYPE_SPECIAL_ARTICLE:
            case mPageModule::MODULE_TYPE_SPECIAL_NOTE:
                mPageModuleH5Obj::saveModuleSort($sortInfo);
                break;
            case mPageModule::MODULE_TYPE_CARD_BANNER:
                mPageModuleImg::saveModuleImgSort($sortInfo);
                break;
        }
    }

    public function savePageStatus(Request $request, $pageId)
    {
        $status = $request->input('status', null);
        $app_status = $request->input('app_status', null);
        $mini_status = $request->input('mini_status', null);
        $message = '修改成功';
        $result = false;
        try {
            $pageInfo = mPage::getPageInfoById($pageId);

            if (!$pageInfo) {
                throw new \Exception('修改的活动不存在');
            }

            if (isset($status)) {
                $result = mPage::changePageStatusById($pageId, $status == 'on' ? mPage::STATUS_NORMAL : mPage::STATUS_OFFLINE);
            }

            if (isset($app_status)) {
                //App-推荐，改为「展示」的时候，检查是否有小封面，如果没有，提示「请先上传小封面」
                if ($app_status == 'on' && $pageInfo['cover_img_small'] == '') {
                    throw new \Exception('请先上传小封面');
                }

                $result = mPage::changeAppStatusById($pageId, $app_status == 'on' ? mPage::STATUS_NORMAL : mPage::STATUS_OFFLINE);
            }

            if (isset($mini_status)) {
                //商城小程序，从隐藏改为展示的时候，检查是否有大封面，如果没有，提示「请先上传大封面」
                if ($mini_status == 'on' && $pageInfo['cover_img_big'] == '') {
                    throw new \Exception('请先上传大封面');
                }

                $result = mPage::changeMiniStatusById($pageId, $mini_status == 'on' ? mPage::STATUS_NORMAL : mPage::STATUS_OFFLINE);
            }

            if (!$result) {
                throw new \Exception('修改失败');
            }

            $status = true;
        } catch (\Exception $e) {
            $message = $e->getMessage();
            $status = false;
        }
        $response = compact('status', 'message');
        return response()->json($response);
    }

    public function delPage($pageId)
    {
        $result = mPage::changePageStatusById($pageId, mPage::STATUS_DELETE);
        if ($result) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "删除失败",
            ]);
        }
    }

    public function delModule($pageId, $moduleId)
    {
        $result = mPageModule::chageModuleStatusById($moduleId, mPageModule::STATUS_DELETE);
        if ($result) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "删除失败",
            ]);
        }
    }

    public function delModuleItem($pageId, $moduleId, $itemId)
    {
        $moduleInfo = mPageModule::getModuleInfoByModuleId($moduleId);
        $result = false;
        switch ($moduleInfo['type']) {
            case mPageModule::MODULE_TYPE_IMG:
                $result = mPageModuleImg::chageImgStatusById($itemId, mPageModuleImg::STATUS_DELETE);
                break;
            case mPageModule::MODULE_TYPE_GOODS:
            case mPageModule::MODULE_TYPE_SPECIAL_GOODS:
                $result = mPageModuleGoods::chageGoodsStatusById($itemId, mPageModuleGoods::STATUS_DELETE);
                break;
            case mPageModule::MODULE_TYPE_WIKI:
                $result = mPageModuleWiki::chageWikiStatusById($itemId, mPageModuleWiki::STATUS_DELETE);
                break;
            case mPageModule::MODULE_TYPE_CARD_BANNER:
                $result = mPageModuleImg::chageImgStatusById($itemId, mPageModuleImg::STATUS_DELETE);
                break;
            case mPageModule::MODULE_TYPE_CARD_ARTICLE:
            case mPageModule::MODULE_TYPE_CARD_WATERFALL:
                $result = mPageModuleArticle::changeStatusById($itemId, mPageModuleArticle::STATUS_DELETE);
                break;
            case mPageModule::MODULE_TYPE_SPECIAL_ARTICLE:
            case mPageModule::MODULE_TYPE_SPECIAL_NOTE:
                $result = mPageModuleH5Obj::changeStatusById($itemId, mPageModuleH5Obj::STATUS_DELETE);
                break;
        }
        if ($result) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "删除失败",
            ]);
        }
    }

    public static function formatLink($inputLinkUrl)
    {
        $linkUrl = $inputLinkUrl;
        preg_match("/^hhz:\/\/./", $linkUrl, $re);
        if ($re) {
            $linkUrl = BizUrl::SCHEME_APP_BASE64 . '://' . base64_encode($linkUrl);
        }
        return $linkUrl;
    }

    public function saveModuleItem(Request $request, $pageId, $moduleId, $itemId)
    {
        $moduleInfo = mPageModule::getModuleInfoByModuleId($moduleId);
        tLog::info('活动::' . __FUNCTION__, compact('pageId', 'moduleId', 'moduleInfo'));
        switch ($moduleInfo['type']) {
            case mPageModule::MODULE_TYPE_GOODS:
            case mPageModule::MODULE_TYPE_SPECIAL_GOODS:
                $name = $request->input("name");
                $value = $request->input("value");
                $result = mPageModuleGoods::updateModuleGoods($itemId, [$name => $value]);
                break;
            case mPageModule::MODULE_TYPE_WIKI:
                $name = $request->input("name");
                $value = $request->input("value");
                $result = mPageModuleWiki::updateModuleWiki($itemId, [$name => $value]);
                break;
            case mPageModule::MODULE_TYPE_IMG:
            case mPageModule::MODULE_TYPE_CARD_BANNER:
                $linkType = $request->input("link_type");
                $linkParams = $request->input("link_params") ? json_encode($request->input("link_params"), JSON_UNESCAPED_UNICODE) : '';
                $result = mPageModuleImg::updateModuleImg($itemId, [
                    'link_type' => $linkType,
                    'link_params' => $linkParams,
                ]);
                break;
        }
        if ($result) {
            return response()->json([
                'status' => true,
                'message' => "修改成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "修改成功",
            ]);
        }
    }

    private static function filterIds($ids)
    {
        $ids = str_replace(PHP_EOL, ',', $ids);
        $ids = array_filter(array_map(function ($id) {
            $id = trim($id);
            if (!empty($id)) {
                return $id;
            } else {
                return null;
            }
        }, explode(",", $ids)));
        return array_values($ids);
    }

    public function addModuleSpecialGoods(Request $request, $pageId, $moduleId)
    {
        $itemId = $request->input("id", 0);
        $goods_id = $request->input("goods_id", 0);
        $uid = $request->input("uid", 0);
        $comment = $request->input("user_comment", '');
        $discount_icon = $request->input("discount_icon", '');
        $goods_desc = $request->input("goods_desc", '');
        $describe = $request->input("goods_describe", '');

        try {
            //数量检查
            if (empty($goods_id)) {
                throw new \Exception('商品id不能为空');
            }

            if ($itemId) {
                $upData = [
                    'goods_id' => $goods_id,
                    'goods_desc' => $goods_desc,
                    'uid' => $uid,
                    'user_comment' => $comment,
                    'discount_icon' => $discount_icon,
                    'goods_describe' => $describe,
                ];
                mPageModuleGoods::updateModuleGoods($itemId, $upData);
            } else {
                $addData = [
                    'page_id' => $pageId,
                    'module_id' => $moduleId,
                    'goods_id' => $goods_id,
                    'goods_desc' => $goods_desc,
                    'uid' => $uid,
                    'user_comment' => $comment,
                    'goods_describe' => $describe,
                    'discount_icon' => $discount_icon,
                    'status' => mPageModuleGoods::STATUS_NORMAL,
                    'addtime' => date('Y-m-d H:i:s')
                ];
                mPageModuleGoods::insertModuleGoods($addData);
            }

            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/activity/page/' . $pageId . '/edit/' . $moduleId . '/edit?active=1')->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '保存失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function addSpecialArticle(Request $request, $pageId, $moduleId)
    {
        $itemId = $request->input("id", 0);
        $obj_id = $request->input("obj_id", '');
        $pic_id = $request->input("pic_id", '');
        $obj_title = $request->input("obj_title", '');
        $obj_tag = $request->input("obj_tag", '');

        try {
            //数量检查
            if (empty($obj_id)) {
                throw new \Exception('内容id为空');
            }

            mPageModuleH5Obj::addModuleH5ObjData([
                'page_id' => $pageId,
                'module_id' => $moduleId,
                'obj_id' => $obj_id,
                'pic_id' => $pic_id,
                'obj_title' => $obj_title,
                'obj_tag' => $obj_tag,
            ], $itemId);

            $success = new MessageBag([
                'title' => '添加成功'
            ]);
            return redirect('/admin/activity/page/' . $pageId . '/edit/' . $moduleId . '/edit?active=1')->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '添加失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function addModuleMultiCard(Request $request, $pageId, $moduleId)
    {
        $itemId = $request->input("item_id", 0);
        $link_params_map = [];
        $obj_ids = [];
        if ($itemId > 0) {
            $obj = $request->input("article", []);
            $link_type = $obj['link_type'] ?? '';
            $link_params = isset($obj['link_params']) ? json_encode($obj['link_params'], JSON_UNESCAPED_UNICODE) : '';
            $objRs = BlockTypeMapping::getObjFromLinkParams($link_type, $link_params);
            $obj_id = $objRs['obj_id'] ?? null;
            $obj_type = $objRs['obj_type'] ?? null;
            $link_params_map[$obj_id] = $link_params;
            $obj_ids = $obj_id ? [$obj_id] : [];
        } else {
            $obj_type = $request->input("article_type", -1);
            $obj_id = $request->input("article_id", '');
            $link_type = BlockTypeMapping::getLinkType($obj_type);
            $obj_ids = self::filterIds($obj_id);
            foreach ($obj_ids as $v) {
                $link_params_map[$v] = BlockTypeMapping::getParamsTpl($link_type, $v);
            }
        }

        try {
            //数量检查
            if (empty($obj_ids)) {
                throw new \Exception('卡片id为空');
            }

            $list = mPageModuleArticle::getModuleArticles($pageId, $moduleId);
            foreach ($list as $v) {
                if ($v['article_type'] == $obj_type && in_array($v['aid'], $obj_ids) && $itemId == $v['id']) {
                    throw new \Exception('添加的卡片信息已经存在');
                }
            }

            foreach ($obj_ids as $aid) {
                mPageModuleArticle::addModuleArticleByData([
                    'page_id' => $pageId,
                    'module_id' => $moduleId,
                    'article_type' => $obj_type,
                    'aid' => $aid,
                    'link_type' => $link_type,
                    'link_params' => $link_params_map[$aid],
                ], $itemId);
            }

            $success = new MessageBag([
                'title' => '添加成功'
            ]);
            return redirect('/admin/activity/page/' . $pageId . '/edit/' . $moduleId . '/edit?active=1')->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '添加失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function addModuleCard(Request $request, $pageId, $moduleId)
    {
        $aIds = $request->input('article_id');
        $articleType = $request->input('article_type');
        $aIds = self::filterIds($aIds);
        try {
            //类型校验
            if (!key_exists($articleType, mPageModuleArticle::ADMIN_ARTICLE_TYPE_MAP)) {
                throw new \Exception('类型不允许');
            }

            //数量检查
            $exists = mPageModuleArticle::getModuleArticle($pageId, $moduleId);
            if (empty($aIds)) throw new \Exception('未输入文章ID');

            //查询文章信息
            if ($articleType == mPageModuleArticle::ARTICLE_TYPE_HOUSE) {
                $articles = mArticle::getAllArticles($aIds);
                $articles = empty($articles) ? [] : array_column($articles, null, 'aid');
            } elseif ($articleType == mPageModuleArticle::ARTICLE_TYPE_TEXT) {
                $articles = Blank::getBlankForSecPage($aIds, $uid = 0);
            } else {
                $articles = Guide::getGuideByIdsALl($aIds);
            }

            foreach ($aIds as $key => $id) {
                if (in_array($id, $exists) || !isset($articles[$id])) {
                    unset($aIds[$key]);
                }
            }

            if (empty($aIds)) throw new \Exception('未输入文章ID,或者ID错误,或者ID已经存在');

            if (count($exists) + count($aIds) > 10) {
                throw new \Exception('最多支持10个内容');
            }

            mPageModuleArticle::addModuleArticle($pageId, $moduleId, $articleType, $aIds);

            $success = new MessageBag([
                'title' => '添加成功'
            ]);
            return redirect('/admin/activity/page/' . $pageId . '/edit/' . $moduleId . '/edit?active=1')->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '添加失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function addModuleGoods(Request $request, $pageId, $moduleId)
    {
        $goodsIds = $request->input('goods_id');
        $goodsIds = str_replace(PHP_EOL, ',', $goodsIds);
        $goodsIds = array_filter(array_map(function ($goodsId) {
            $goodsId = trim($goodsId);
            if (ctype_digit($goodsId)) {
                return $goodsId;
            } else {
                return null;
            }
        }, explode(",", $goodsIds)));
        if ($goodsIds) {
            mPageModuleGoods::addModuleGoods($pageId, $moduleId, $goodsIds);
            $success = new MessageBag([
                'title' => '添加成功'
            ]);
            return redirect('/admin/activity/page/' . $pageId . '/edit/' . $moduleId . '/edit?active=1')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '添加失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    public function addSpecialGoods(Request $request, $pageId, $moduleId)
    {
        $goodsIds = $request->input('goods_id');
        $goodsIds = str_replace(PHP_EOL, ',', $goodsIds);
        $goodsIds = array_filter(array_map(function ($goodsId) {
            $goodsId = trim($goodsId);
            if (ctype_digit($goodsId)) {
                return $goodsId;
            } else {
                return null;
            }
        }, explode(",", $goodsIds)));
        if ($goodsIds) {
            mPageModuleGoods::addModuleGoods($pageId, $moduleId, $goodsIds);
            $success = new MessageBag([
                'title' => '添加成功'
            ]);
            return redirect('/admin/activity/page/' . $pageId . '/edit/' . $moduleId . '/edit?active=1')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '添加失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    public function addModuleWiki(Request $request, $pageId, $moduleId)
    {
        $wikiIds = $request->input('wiki_id');
        $wikiIds = str_replace(PHP_EOL, ',', $wikiIds);
        $wikiIds = array_filter(array_map(function ($wikiId) {
            $wikiId = trim($wikiId);
            if (ctype_digit($wikiId)) {
                return $wikiId;
            } else {
                return null;
            }
        }, explode(",", $wikiIds)));
        if ($wikiIds) {
            mPageModuleWiki::addModuleWiki($pageId, $moduleId, $wikiIds);
            $success = new MessageBag([
                'title' => '添加成功'
            ]);
            return redirect('/admin/activity/page/' . $pageId . '/edit/' . $moduleId . '/edit?active=1')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '添加失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    public function addModuleImgs(Request $request, $pageId, $moduleId)
    {
        $images = $request->input('images');
        $images = array_filter(explode(",", $images));

        if ($images ) {
            $moduleInfo = mPageModule::getModuleInfoByModuleId($moduleId);
            if (mPageModule::MODULE_TYPE_CARD_BANNER == $moduleInfo['type']) {
                $exists = mPageModuleImg::getImgByModuleId($moduleId);
                if (count($exists) + count($images) > 10) {
                    throw new \Exception('最多支持10个内容');
                }
            }

            mPageModuleImg::addModuleImg($pageId, $moduleId, $images);
            $success = new MessageBag([
                'title' => '添加成功'
            ]);
            return redirect('/admin/activity/page/' . $pageId . '/edit/' . $moduleId . '/edit?active=1')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '添加失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    /**
     * 活动页添加模块
     * @param Content $content
     * @param $id int 活动页id
     * @param $type int 模块id
     * @return Content
     */
    public function moduleAdd(Content $content, $id, $type)
    {
        $tab = new Tab();
        $tab->add('模块基础信息', $this->_getModuleForm($id, null, $type));
        return $content
            ->header('添加' . mPageModule::MODULE_TYPE_VIEW[$type])
            ->breadcrumb(
                [
                    'text' => '活动列表',
                    'url' => '/activity/page'
                ],
                [
                    'text' => '活动详情',
                    'url' => '/activity/page/' . $id . '/edit'
                ],
                ['text' => '添加' . mPageModule::MODULE_TYPE_VIEW[$type]]
            )
            ->row($tab);
    }

    /**
     * @desc 编辑模块
     * @param Request $request
     * @param Content $content
     * @param $pageId
     * @param $moduleId
     * @return Content
     * @throws \Exception
     */
    public function moduleEdit(Request $request, Content $content, $pageId, $moduleId)
    {
        $tab = new Tab();
        $moduleBaseInfo = mPageModule::getModuleInfoByModuleId($moduleId);
        $type = $moduleBaseInfo['type'];
        $tabTitle = "";

        switch ($type) {
            case mPageModule::MODULE_TYPE_IMG:
                $grid = $this->_getImgModuleGrid($pageId, $moduleId);
                $tabTitle = "图片列表";
                break;
            case mPageModule::MODULE_TYPE_GOODS:
                $grid = $this->_getGoodsModuleGrid($pageId, $moduleId);
                $tabTitle = "商品列表";
                break;
            case mPageModule::MODULE_TYPE_WIKI:
                $moduleBaseInfo['jump'] = $moduleBaseInfo['ext']['jump'];
                $grid = $this->_getWikiModuleGrid($pageId, $moduleId);
                $tabTitle = "WIKI列表";
                break;
            case mPageModule::MODULE_TYPE_SPECIAL_GOODS:
                $grid = $this->_getSpecialGoodsModuleGrid($pageId, $moduleId);
                $tabTitle = "商品列表";
                break;
            case mPageModule::MODULE_TYPE_CARD_BANNER:
            case mPageModule::MODULE_TYPE_CARD_ARTICLE:
                $tabTitle = "卡片列表";
                $grid = $this->_getCardModuleGrid($pageId, $moduleId, $type);
                break;
            case mPageModule::MODULE_TYPE_CARD_WATERFALL:
                $tabTitle = "瀑布流列表";
                $grid = $this->_getCardWaterfallModuleGrid($pageId, $moduleId);
                break;
            case mPageModule::MODULE_TYPE_FLOAT:
                $moduleBaseInfo['bgcolor'] = $moduleBaseInfo['ext']['bgcolor'];
                $moduleBaseInfo['link'] = $moduleBaseInfo['ext'];
                break;
            case mPageModule::MODULE_TYPE_WATERFALL:
                $moduleBaseInfo['is_show_num'] = $moduleBaseInfo['ext']['is_show_num'];
                $moduleBaseInfo['ext']['topic_id'] = is_array($moduleBaseInfo['ext']['topic_id']) ? $moduleBaseInfo['ext']['topic_id'] : explode(",", $moduleBaseInfo['ext']['topic_id']);
                foreach ($moduleBaseInfo['ext']['topic_id'] as $topicId) {
                    if ($topicId) {
                        if (strpos($topicId, PageModule::MODULE_WATERFALL_TAB_DELIMITER) === false) {
                            $moduleBaseInfo['topic_id'][] = $topicId . PageModule::MODULE_WATERFALL_TAB_DELIMITER . sTopicTab::DEFAULT_TAB_HOT;
                        } else {
                            $moduleBaseInfo['topic_id'][] = $topicId;
                        }
                    }
                }
                break;
            case mPageModule::MODULE_TYPE_VIDEO:
                $moduleBaseInfo['link'] = $moduleBaseInfo['ext']['link'];
                $moduleBaseInfo['pic_id'] = $moduleBaseInfo['ext']['pic_id'];
                break;
            case mPageModule::MODULE_TYPE_ANCHOR:
                $moduleBaseInfo['bg_color'] = $moduleBaseInfo['ext']['bg_color'] ?? '';
                $moduleBaseInfo['text_color'] = $moduleBaseInfo['ext']['text_color'] ?? '';
                break;
            case mPageModule::MODULE_TYPE_FOLLOW:
                $uid = $moduleBaseInfo['ext']['uid'];
                $moduleBaseInfo['uid'] = $uid;
                $userInfo = User::getUserInfo($uid);
                $moduleBaseInfo['uid_help'] = isset($userInfo['type']) && $userInfo['type'] == Member::AUTH_USER_BRAND ? '品牌账号' : "非品牌账号";
                $moduleBaseInfo['obj'] = [
                    'link_type' => $moduleBaseInfo['ext']['link_type'],
                    'link_params' => $moduleBaseInfo['ext']['link_params'],
                ];

                $moduleBaseInfo['pic_base_id'] = $moduleBaseInfo['ext']['card_info']['pic_base_id'];
                $moduleBaseInfo['pic_bg_id'] = $moduleBaseInfo['ext']['card_info']['pic_bg_id'];
                $moduleBaseInfo['name_color'] = $moduleBaseInfo['ext']['card_info']['name_color'];
                $moduleBaseInfo['content_color'] = $moduleBaseInfo['ext']['card_info']['content_color'];
                $moduleBaseInfo['button_color'] = $moduleBaseInfo['ext']['button_color'];
                $moduleBaseInfo['text_color'] = $moduleBaseInfo['ext']['text_color'];
                break;
            case mPageModule::MODULE_TYPE_DESIGNER:
                $uid = $moduleBaseInfo['ext']['uid'];
                $moduleBaseInfo['uid'] = $uid;
                $userInfo = User::getUserInfo($uid);
                $moduleBaseInfo['uid_help'] = isset($userInfo['type']) && $userInfo['type'] == Member::AUTH_USER_BRAND ? '品牌账号' : "非品牌账号";
                $moduleBaseInfo['obj'] = [
                    'link_type' => $moduleBaseInfo['ext']['link_type'],
                    'link_params' => $moduleBaseInfo['ext']['link_params'],
                ];
                $moduleBaseInfo['custom_title'] = $moduleBaseInfo['ext']['custom_title'];
                $moduleBaseInfo['custom_img'] = $moduleBaseInfo['ext']['custom_img'];
                $moduleBaseInfo['button_color'] = $moduleBaseInfo['ext']['button_color'];
                $moduleBaseInfo['text_color'] = $moduleBaseInfo['ext']['text_color'];
                break;
            case mPageModule::MODULE_TYPE_SPECIAL_ARTICLE:
                $button_color = $moduleBaseInfo['ext']['button_color'] ?? '';
                $moduleBaseInfo['button_color'] = $button_color;
                $tabTitle = "整屋卡片列表";
                $grid = $this->_getSpecialArticleModuleGrid($pageId, $moduleId);
                break;
            case mPageModule::MODULE_TYPE_SPECIAL_NOTE:
                $button_color = $moduleBaseInfo['ext']['button_color'] ?? '';
                $moduleBaseInfo['button_color'] = $button_color;
                $tabTitle = "note卡片列表";
                $grid = $this->_getSpecialArticleModuleGrid($pageId, $moduleId, true);
                break;
            case mPageModule::MODULE_TYPE_GOODS_SET:
                $moduleBaseInfo['top_wiki_ids'] = $moduleBaseInfo['ext']['top_wiki_ids'];
                $moduleBaseInfo['topic_ids'] = $moduleBaseInfo['ext']['topic_ids'];
                $moduleBaseInfo['bg_img'] = $moduleBaseInfo['ext']['bg_img'];
                break;
            case mPageModule::MODULE_TYPE_BLIND_BOX:
                $moduleBaseInfo['bg_img'] = $moduleBaseInfo['ext']['bg_img'];
                $moduleBaseInfo['btn_before'] = $moduleBaseInfo['ext']['btn_before'];
                $moduleBaseInfo['btn_after'] = $moduleBaseInfo['ext']['btn_after'];
                break;
            case mPageModule::MODULE_TYPE_MULTI_FOLLOW:
                $moduleBaseInfo['pic_id'] = $moduleBaseInfo['ext']['pic_id'];
                $moduleBaseInfo['done_pic_id'] = $moduleBaseInfo['ext']['done_pic_id'];
                break;
            case mPageModule::MODULE_TYPE_CPL:
                $basic_field =  array_filter($moduleBaseInfo['ext']['basic_field'],function ($val){
                     return $val ? : false;
                });
                $moduleBaseInfo['basic_field'] = array_keys($basic_field);
                $moduleBaseInfo['desc'] = $moduleBaseInfo['ext']['desc'] ? : '';
                $moduleBaseInfo['submit_desc'] = $moduleBaseInfo['ext']['submit_desc']? : '';
                $moduleBaseInfo['is_show_joiner_data'] =$moduleBaseInfo['ext']['is_show_joiner_data'] ? : 0;


                break;
            case mPageModule::MODULE_TYPE_SHOP_BOOK:
                $moduleBaseInfo['pic_id'] = $moduleBaseInfo['ext']['pic_id'] ?? '';
                $moduleBaseInfo['shop_id'] = $moduleBaseInfo['ext']['shop_id'] ?? '';
                break;
        }

        //活动页信息
        $pageInfo = mPage::getPageInfoById($pageId);

        $form = $this->_getModuleForm($pageId, $moduleBaseInfo, $type);
        $tab->add('模块基础信息', $form);
        if (isset($grid)) $tab->add($tabTitle, $grid, true);
        $typeName = mPageModule::getModuleTypeName($type);
        return $content
            ->header('编辑' . $typeName)
            ->breadcrumb(
                [
                    'text' => '活动列表',
                    'url' => '/activity/page'
                ],
                [
                    'text' => "活动页[{$pageInfo['title']}]配置",
                    'url' => '/activity/page/' . $pageId . '/edit'
                ],
                ['text' => '编辑' . $typeName]
            )
            ->row($tab);
    }

    public function getObjTitle(Request $request)
    {
        $obj_id = $request->input('obj_id', '');
        $objType = IdParse::getType($obj_id);
        $contentMap = AdmContent::get($objType, $obj_id);
        $info = $contentMap[$obj_id] ?? [];
        $title = $info['title'] ?? '';
        return response()->json(compact('title', 'obj_id'));
    }

    /**
     * @desc 编辑模块
     * @param Request $request
     * @param Content $content
     * @param $pageId
     * @param $moduleId
     * @param $itemId
     * @return Content
     * @throws \Exception
     */
    public function moduleItemAdd(Request $request, Content $content, $pageId, $moduleId, $itemId = 0)
    {
        //活动页信息
        $pageInfo = mPage::getPageInfoById($pageId);

        //模块信息
        $moduleBaseInfo = mPageModule::getModuleInfoByModuleId($moduleId);
        $type = $moduleBaseInfo['type'];
        $typeName = mPageModule::getModuleTypeName($type);

        switch ($type) {
            case mPageModule::MODULE_TYPE_SPECIAL_ARTICLE:
                $header = $itemId > 0 ? '编辑整屋卡片信息' : '添加整屋卡片信息';
                $info = $itemId > 0 ? mPageModuleH5Obj::get('*', ['id' => $itemId]) : [];
                $form = new Form($info);
                $form->hidden('id');
                $form->text('obj_id', '整屋id');
                $form->imgUpload('pic_id', '运营上传整屋封面');
                $form->text('obj_title', '整屋标题')->help('22字以内，含标点符号');
                $form->text('obj_tag', '关键词标签')->help('总字数不超过18个;多个标签用,隔开');
                $form->action("/admin/activity/page/$pageId/module/$moduleId/addSpecialArticle");
                //script
                $script = <<<EOT
(function () {
	$(':input[name="obj_id"]').on('blur', function () {
	    var obj_id = this.value;
	    if ($(':input[name="obj_title"]').val() != '') {
	        return ;
	    }
        $.ajax({
            url:"/admin/activity/page/getObjTitle",
            type:"GET",
            data:{obj_id : obj_id},
            dataType:"json",
            success:function(result){
                if (result.title.length > 0) {
                    $(':input[name="obj_title"]').val(result.title);
                }
            }
        });
	});
})();
EOT;
                Admin::script($script);
                break;
            case mPageModule::MODULE_TYPE_SPECIAL_NOTE:
                $header = $itemId > 0 ? '编辑note卡片信息' : '添加note卡片信息';
                $info = $itemId > 0 ? mPageModuleH5Obj::get('*', ['id' => $itemId]) : [];
                $form = new Form($info);
                $form->hidden('id');
                $form->text('obj_id', 'note id');
                $form->imgUpload('pic_id', '运营上传note封面')->help('宽高比 1 : 1');
                $form->text('obj_tag', '运营填写关键词')->help('最多4个汉字/8个英文字母;例如:住友范例');
                $form->action("/admin/activity/page/$pageId/module/$moduleId/addSpecialArticle");
                break;
            case mPageModule::MODULE_TYPE_SPECIAL_GOODS:
                $header = $itemId > 0 ? '编辑商品展示信息' : '新增商品展示信息';
                $info = $itemId > 0 ? mPageModuleGoods::get('*', ['id' => $itemId]) : [];
                $form = new Form($info);
                $form->hidden('id');
                $form->text('goods_id', '商品id');
                $form->text('uid', '用户评论uid');
                $form->textarea('user_comment', '用户评论');
//                $form->imgUpload('discount_icon', '优惠图标');
                $form->text('goods_desc', '特殊说明');
                $form->text('goods_describe', '卖点');
                $form->action("/admin/activity/page/$pageId/module/$moduleId/addSpecialGoods");
                break;
            default:
                //模块子项信息
                $info = $itemId > 0 ? mPageModuleArticle::get('*', ['id' => $itemId]) : [];
                $info = empty($info) ? [] : [
                    'article' => $info,
                    'item_id' => $itemId
                ];

                $form = new Form($info);
                $form->hidden('item_id');
                if ($itemId > 0) {
                    $form->multiLinkSelect('article', '卡片');
                } else {
                    $form->select('article_type', '卡片类型')->options(mPageModuleArticle::ADMIN_ARTICLE_TYPE_MAP)->default(mPageModuleArticle::ARTICLE_TYPE_HOUSE);
                    $form->textarea('article_id', '卡片ID')->help('多个ID用,分隔');
                }

                $form->action("/admin/activity/page/$pageId/module/$moduleId/addMultiCard");
                $header = $itemId > 0 ? '编辑卡片' : '新增卡片';
                break;
        }

        return $content
            ->header($header)
            ->breadcrumb(
                [
                    'text' => '活动列表',
                    'url' => '/activity/page'
                ],
                [
                    'text' => "活动页[{$pageInfo['title']}]配置",
                    'url' => '/activity/page/' . $pageId . '/edit'
                ],
                [
                    'text' => '编辑' . $typeName,
                    'url' => "/activity/page/$pageId/edit/$moduleId/edit"
                ],
                ['text' => $header]
            )
            ->row($form);
    }

    /**
     * 活动页添加模块
     * @param $pageId
     * @param $moduleInfo
     * @param int $moduleType
     * @return Form
     */
    private function _getModuleForm($pageId, $moduleInfo, $moduleType = 1)
    {
        $form = new Form($moduleInfo);
        switch ($moduleType) {
            case mPageModule::MODULE_TYPE_MULTI_FOLLOW:
                $form->imgUpload('pic_id', '一键关注图');
                $form->imgUpload('done_pic_id', '已关注图');
                break;
            case mPageModule::MODULE_TYPE_FLOAT:
                $form->text('title', '文字内容');
                $form->color('bgcolor', '背景色')->hex();
                $form->linkSelect('link', '跳转链接');
                break;
            case mPageModule::MODULE_TYPE_VIDEO:
                $form->text('title', '视频标题');
                $form->imgUpload('pic_id', '视频封面图');
                $form->text('link', '视频链接');
                break;
            case mPageModule::MODULE_TYPE_FOLLOW:
                if (isset($moduleInfo['uid']) && $moduleInfo['uid'] > 0) {
                    $form->text('uid', '用户ID')->required()->help($moduleInfo['uid_help']);
                    $config_base = $moduleInfo['pic_base_id'] ? ['isUpload' => true, 'isGetUrl' => true] : [];
                    $config_bg = $moduleInfo['pic_bg_id'] ? ['isUpload' => true, 'isGetUrl' => true] : [];
                    $form->imgUpload('pic_base_id', '名片底图', true, $config_base)->help('仅支持上传一张,默认白底图');
                    $form->imgUpload('pic_bg_id', '名片背景', true, $config_bg)->help('仅支持上传一张,默认浅灰色');
                } else {
                    $form->text('uid', '用户ID')->required();
                    $form->imgUpload('pic_base_id', '名片底图')->help('仅支持上传一张,默认白底图');
                    $form->imgUpload('pic_bg_id', '名片背景')->help('仅支持上传一张,默认浅灰色');
                }
                $form->color('button_color', '关注按钮的背景色')->help('控制未关注状态时');
                $form->color('text_color', '关注按钮的文字颜色')->help('控制未关注状态时');
                $form->radio('name_color', '名称颜色')
                    ->options([1 => '黑色', 2 => '白色'])
                    ->default($moduleInfo['name_color'] ?? 1);
                $form->radio('content_color', '内容颜色')
                    ->options([1 => '黑色', 2 => '白色'])
                    ->default($moduleInfo['content_color'] ?? 1);
                $allowLink = [
                    LinkConf::LINK_ARTICLE,
                    LinkConf::LINK_GUIDE,
                    LinkConf::LINK_BLANK,
                ];
                $form->multiLinkSelect('obj', '内容卡片', $allowLink)->help('仅支持整屋案例、指南文章、经验文章');

                break;
            case mPageModule::MODULE_TYPE_DESIGNER:
                $form->text('uid', '设计师uid')->required();
                $allowLink = [
                    LinkConf::LINK_ARTICLE,
                    LinkConf::LINK_GUIDE,
                    LinkConf::LINK_BLANK,
                ];
                $form->multiLinkSelect('obj', '内容卡片', $allowLink)->help('仅支持整屋案例、指南文章、经验文章');
                $form->text('custom_title', '自定义标题');
                $form->imgUpload('custom_img', '自定义图片');
                $form->color('button_color', '关注按钮的背景色')->help('控制未关注状态时');
                $form->color('text_color', '关注按钮的文字颜色')->help('控制未关注状态时');
                break;
            case mPageModule::MODULE_TYPE_ANCHOR:
                $form->color('bg_color', '导航背景色')->help('控制选中状态');
                $form->color('text_color', '导航文字颜色')->help('控制选中状态');
                break;
            case mPageModule::MODULE_TYPE_WATERFALL:
                $form->text('title', '模块标题');
                $form->radio('is_show_num', '是否展示参与数')
                    ->options([
                        1 => '展示',
                        2 => '不展示'
                    ])
                    ->default($moduleInfo['is_show_num'] ?? mPageModule::MODULE_WATERFALL_HIDE_NUM);
                //获取当前所有的话题列表
                $topics = TopicActivity::getAllTopic();
                $topicTabs = TopicTab::getAllTabs();
                $formatTopicTabs = [];
                foreach ($topicTabs as $topicTab) {
                    $formatTopicTabs[$topicTab['topic_id']][] = $topicTab;
                }
                $formatTopicOptions = [];
                foreach ($topics as $topic) {
                    $formatTopicOptions[$topic['id'] . PageModule::MODULE_WATERFALL_TAB_DELIMITER . sTopicTab::DEFAULT_TAB_HOT] = "[{$topic['id']}][热门-热度排序]{$topic['title']}";
                    $formatTopicOptions[$topic['id'] . PageModule::MODULE_WATERFALL_TAB_DELIMITER . sTopicTab::DEFAULT_TAB_NEW] = "[{$topic['id']}][最新-时间排序]{$topic['title']}";
                    if (isset($formatTopicTabs[$topic['id']])) {
                        foreach ($formatTopicTabs[$topic['id']] as $tab) {
                            $formatTopicOptions[$topic['id'] . PageModule::MODULE_WATERFALL_TAB_DELIMITER . $tab['id']] = "[{$topic['id']}][{$tab['title']}-热度排序]{$topic['title']}";
                        }
                    }
                }
                $form->multipleSelect('topic_id', '话题Tab')->options($formatTopicOptions)->required()->help('为了统一排序规则，选择多个话题Tab只能选择相同的排序规则的话题Tab');
                break;
            case mPageModule::MODULE_TYPE_SPECIAL_ARTICLE:
            case mPageModule::MODULE_TYPE_SPECIAL_NOTE:
                $form->radio('style', "展现样式")
                    ->options([
                        mPageModule::MODULE_STYLE_ONE => "一行一个",
                        mPageModule::MODULE_STYLE_TWO => "一行两个",
                    ])
                    ->default(mPageModule::MODULE_STYLE_ONE)->help('提示：整屋一行一个 note一行两个');

                $form->color('button_color', '按钮配色');
                break;
            case mPageModule::MODULE_TYPE_CARD_BANNER:
            case mPageModule::MODULE_TYPE_CARD_ARTICLE:
                $form->text('title', '标题');
                break;
            case mPageModule::MODULE_TYPE_CARD_WATERFALL:
                $form->text('title', '标题');
                $form->radio('style', "展现样式")
                    ->options([
                        mPageModule::MODULE_STYLE_ONE => "一行一个",
                        mPageModule::MODULE_STYLE_TWO => "一行两个",
                    ])
                    ->default(mPageModule::MODULE_STYLE_ONE)->help('提示：若添加整屋瀑布流，可选择一行一个 or 一行两个；其余均只支持一行两个');
                break;
            case mPageModule::MODULE_TYPE_GOODS_SET:
                $form->text('top_wiki_ids', '置顶wiki集合')->required()
                    ->default($moduleInfo['top_wiki_ids'] ?? '')
                    ->help('提示：最多添加6个wiki_id, 用英文","分隔例如->1,2,3');
                $form->text('topic_ids', '话题id')->required()
                    ->default($moduleInfo['topic_ids'] ?? '')
                    ->help('提示：仅支持一个话题');
                if ($moduleInfo['bg_img']) {
                    $form->imgUpload('bg_img', '背景', true, ['isUpload' => true, 'isGetUrl' => true])->help('仅支持上传一张,默认浅灰色');
                } else {
                    $form->imgUpload('bg_img', '背景')->help('仅支持上传一张,默认浅灰色');
                }
                break;
                
            case mPageModule::MODULE_TYPE_BLIND_BOX:
                $form->imgUpload('bg_img', '背景')->help('仅支持上传一张');
                $form->imgUpload('btn_before', '按钮1-抽奖前')->help('仅支持上传一张');
                $form->imgUpload('btn_after', '按钮2-抽奖后')->help('仅支持上传一张');
                break;
            case mPageModule::MODULE_TYPE_CPL:
                $form->checkbox('basic_field', '选择基础字段')->options(['name' => '姓名', 'phone' => '电话号码' ,'area' => '地区'])->default(['name' ,'phone'])->help("强制勾选姓名与电话号码 ，如需所在地区自行勾选");
                $form->text('desc', '说明文案')->help("建议文字不超过68个字");
                $form->text('submit_desc', '提交按钮文案')->help('建议提交按钮文案不超过8个字，默认 ： 提交报告');
                $form->radio('is_show_joiner_data', "是否展示参与数据")
                    ->options([1 => '展示参与数据' ,0 =>"不展示" ])->default(1)->help("表单下方显示已提交报名人数");



                break;
            case mPageModule::MODULE_TYPE_WIKI:
                $form->text('title', '模块标题');
                $form->radio('style', "展现样式")->options(mPageModule::MODULE_SYLE_VIEW)->default(mPageModule::MODULE_STYLE_ONE);
                $form->radio('jump', "跳转页面")->options(['1' => 'wiki详情页', '2' => 'wiki中间页'])->default(1);
                break;
            case mPageModule::MODULE_TYPE_SHOP_BOOK:
                $form->text('title', '模块名称');
                $form->imgUpload('pic_id', '上传图片');
                $form->text('shop_id', '门店 id');
                break;
            default:

                $form->text('title', '模块标题');
                $form->radio('style', "展现样式")
                    ->options(mPageModule::MODULE_SYLE_VIEW)->default(mPageModule::MODULE_STYLE_ONE);
                $form->text('anchor', '锚点');
                $form->text('tab', 'tab锚点');
                break;

        }
        $form->hidden('type')->default($moduleType);
        $form->action('/admin/activity/page/' . $pageId . '/save/' . ($moduleInfo ? $moduleInfo['id'] : 0));
        return $form;
    }

    private function _getSpecialArticleModuleGrid($pageId, $moduleId, $note = false)
    {
        $list = mPageModuleH5Obj::getArticleByModuleId($moduleId);
        $gridModel = new pGridDataModel($list);
        $detailGrid = Admin::grid($gridModel,
            function (Grid $grid) use ($note) {
                $grid->disableFilter();
                $grid->disableExport();
//                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->option('usePagination', false);
                $grid->column('id')->sort();
                if ($note) {
                    $grid->column('pic_url', '运营上传note封面')->image('', 250);
                    $grid->column('obj_tag', '运营填写关键词')->label();
                    $grid->column('link_type', '内容信息')->display(function () {
                        $houseInfo = $this->list_info;
                        $display = [
                            "note id: " . $this->obj_id,
                            isset($houseInfo['title']) ? $houseInfo['title'] : "",
                            isset($houseInfo['status_desc']) ? "状态:" . $houseInfo['status_desc'] : "",
                            $houseInfo['cover_pic_url'] ? "<img width='250' src='{$houseInfo['cover_pic_url']}'>" : "",
                        ];
                        return implode('<br/>', $display);
                    });
                } else {
                    $grid->column('pic_url', '运营上传整屋封面')->image('', 150);
                    $grid->column('obj_title', '运营填写整屋标题')->width(200);
                    $grid->column('obj_tag', '运营填写关键词标签')->label();
                    $grid->column('link_type', '内容信息')->display(function () {
                        $houseInfo = $this->list_info;
                        $display = [
                            "整屋id: " . $this->obj_id,
                            isset($houseInfo['title']) ? $houseInfo['title'] : "",
                            isset($houseInfo['status_desc']) ? "状态:" . $houseInfo['status_desc'] : "",
                            $houseInfo['cover_pic_url'] ? "<img width='150' src='{$houseInfo['cover_pic_url']}'>" : "",
                        ];
                        return implode('<br/>', $display);
                    });
                }

                $grid->actions(function (Grid\Displayers\Actions $actions) {
//                    $actions->disableEdit();
                });
            });
        return $detailGrid->render();
    }

    private function _getCardWaterfallModuleGrid($pageId, $moduleId)
    {
        $list = mPageModuleArticle::getArticleByModuleId($moduleId);
        $gridModel = new pGridDataModel($list);
        $detailGrid = Admin::grid($gridModel,
            function (Grid $grid) {
                $grid->disableFilter();
                $grid->disableExport();
//                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->option('usePagination', false);
                $grid->column('id')->sort();
                $grid->column('link', '卡片信息')->linkSelect(false);
                $grid->column('link_type', '内容信息')->display(function () {
                    $houseInfo = $this->list_info;
                    $display = [
                        isset($houseInfo['title']) ? $houseInfo['title'] : "",
                        isset($houseInfo['status_desc']) ? "状态:" . $houseInfo['status_desc'] : "",
                        $houseInfo['cover_pic_url'] ? "<img width='200' src='{$houseInfo['cover_pic_url']}'>" : "",
                    ];
                    return implode('<br/>', $display);
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
//                    $actions->disableEdit();
                });
            });
        return $detailGrid->render();
    }

    private function _getCardModuleGrid($pageId, $moduleId, $cardType)
    {
        $batchForm = new Form();
        $list = [];
        switch ($cardType) {
            case mPageModule::MODULE_TYPE_CARD_ARTICLE:
                $list = mPageModuleArticle::getArticleByModuleId($moduleId);
                $batchForm->select('article_type', '类型')->options([
                    BlockType::TYPE_ARTICLE => '整屋',
                    BlockType::TYPE_GUIDE => '指南',
                    BlockType::TYPE_BLANK => '文章',
                ])->default(mPageModuleArticle::ARTICLE_TYPE_HOUSE);
                $batchForm->textarea('article_id', '整屋/文章/指南ID')->help('多个ID用,分隔');
                $batchForm->action('/admin/activity/page/' . $pageId . '/module/' . $moduleId . '/addCard');
                break;
            case mPageModule::MODULE_TYPE_CARD_BANNER:
                $list = mPageModuleImg::getImgByModuleId($moduleId);
                $batchForm->imgUpload('images', '上传图片', true);
                $batchForm->action('/admin/activity/page/' . $pageId . '/module/' . $moduleId . '/addImgs');
                break;
        }


        $gridModel = new pGridDataModel($list);
        $detailGrid = Admin::grid($gridModel,
            function (Grid $grid) use ($cardType) {
                $grid->disableFilter();
                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->option('usePagination', false);
                $grid->column('id')->sort();
                if ($cardType == mPageModule::MODULE_TYPE_CARD_ARTICLE) {
                    $grid->column('article_type_desc', '类型');
                    $grid->column('aid', '文章ID');
                    $grid->column('img_url', '文章信息')->display(function () {
                        $houseInfo = $this->house_info;
                        $a = isset($houseInfo['title']) ? $houseInfo['title'] : "";
                        $houseSize = isset($houseInfo['house_size']) && ($houseInfo['house_size'] > 0) ? $houseInfo['house_size'] . '平米' : '';
                        $img = $houseInfo['cover_pic'] ? "<img width='200' src='{$houseInfo['cover_pic']}'>" : "";
                        return implode('<br/>', [
                            $img,
                            $a,
                            $houseSize,
                        ]);
                    });
                } else {
                    $grid->column('img_url', '图片')->image();
                    $grid->column('link', '链接信息')->linkSelect();
                }

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                });
            });
        return $batchForm->render() . $detailGrid->render();
    }

    private function _getImgModuleGrid($pageId, $moduleId)
    {
        $batchForm = new Form();
        $batchForm->imgUpload('images', '上传图片', true);

        $batchForm->action('/admin/activity/page/' . $pageId . '/module/' . $moduleId . '/addImgs');

        $img = mPageModuleImg::getImgByModuleId($moduleId);
        // 展示
        $gridModel = new pGridDataModel($img);
        $detailGrid = Admin::grid($gridModel,
            function (Grid $grid) {
                $grid->disableFilter();
                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->option('usePagination', false);
                $grid->column('id')->sort();
                $grid->column('img_url', '图片')->image();
                $grid->column('link', '链接信息')->linkSelect();
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                });
            });
        return $batchForm->render() . $detailGrid->render();
    }

    private function _getGoodsModuleGrid($pageId, $moduleId)
    {
        $batchForm = new Form();
        $batchForm->textarea('goods_id', '商品ID')->help('多个商品ID用换行分隔');
        $batchForm->action('/admin/activity/page/' . $pageId . '/module/' . $moduleId . '/addGoods');

        $goods = mPageModuleGoods::getGoodsByModuleId($moduleId);
        $gridModel = new pGridDataModel($goods);
        $detailGrid = Admin::grid($gridModel,
            function (Grid $grid) {
                $grid->disableFilter();
                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->option('usePagination', false);
                $grid->column('id')->sort();
                $grid->column('goods_id', '商品ID');
                $grid->column('商品')->display(function () {
                    return "<img src='" . $this->goods_info["cover_img"] . "' style='max-height:100px' class='img img-thumbnail' />" . $this->goods_info["title"];
                })->setAttributes(['class' => 'col-md-6']);
                $grid->column('goods_desc', '描述')->editable('textarea');
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                });
            });
        return $batchForm->render() . $detailGrid->render();
    }

    private function _getWikiModuleGrid($pageId, $moduleId)
    {
        $batchForm = new Form();
        $batchForm->textarea('wiki_id', 'Wiki ID')->help('多个Wiki ID用换行分隔');
        $batchForm->action('/admin/activity/page/' . $pageId . '/module/' . $moduleId . '/addWiki');

        $wiki = mPageModuleWiki::getWikiByModuleId($moduleId);
        $gridModel = new pGridDataModel($wiki);
        $detailGrid = Admin::grid($gridModel,
            function (Grid $grid) {
                $grid->disableFilter();
                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->option('usePagination', false);
                $grid->column('id')->sort();
                $grid->column('wiki_id', 'Wiki ID');
                $grid->column('Wiki')->display(function () {
                    return "<img src='" . $this->wiki_info["cover_img"] . "' style='max-height:100px' class='img img-thumbnail' />" . $this->wiki_info["title"];
                })->setAttributes(['class' => 'col-md-6']);
                $grid->column('wiki_desc', '描述')->editable('textarea');
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                });
                $grid->disablePagination();
            });
        return $batchForm->render() . $detailGrid->render();
    }

    private function _getSpecialGoodsModuleGrid($pageId, $moduleId)
    {
        $wiki = mPageModuleGoods::getSpecialGoodsByModuleId($moduleId);
        $gridModel = new pGridDataModel($wiki);
        $detailGrid = Admin::grid($gridModel,
            function (Grid $grid) {
                $grid->disableFilter();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->option('usePagination', false);
                $grid->column('id')->sort();
                $grid->column('goods_id', '商品id');
                $grid->column('goods_describe', '卖点');
                $grid->column('商品信息')->display(function () {
                    return "<img src='" . $this->goods_info["cover_img"] . "' style='max-height:100px' class='img img-thumbnail' />" . $this->goods_info["title"];
                });
                $grid->column('评论信息')->display(function () {
                    if ($this->uid == 0) return '-';
                    return "<img src='" . $this->user_info["avatar"] . "' style='max-width:50px' class='img img-thumbnail' /><br/>" . $this->user_info['nick'] . '(' . $this->user_info['uid'] . "):" . $this->user_comment;
                });
                $grid->column('特殊说明')->display(function () {
                    return "<img src='" . $this->discount_icon_url . "' style='max-width:100px' class='img img-thumbnail' /><br/>" . $this->goods_desc;
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {

                });
                $grid->disablePagination();
            });
        return $detailGrid->render();
    }

    private function _getPageBaseInfoForm($id = 0)
    {
        if ($id) {
            $specialInfo = mPage::getPageInfoById($id);
        } else {
            $specialInfo = [];
        }

        $baseInfoForm = new Form($specialInfo);
        $baseInfoForm->text('title', '活动标题');
        $baseInfoForm->text('sub_title', '活动副标题');
        if ($id) {
            $baseInfoForm->hidden('page_type');
            $baseInfoForm->radio('page_type', '活动类型')->options(mPage::PAGE_TYPE_DESC)->default(mPage::PAGE_TYPE_MALL)->attribute('disabled', !$id);
        } else {
            $baseInfoForm->radio('page_type', '活动类型')->options(mPage::PAGE_TYPE_DESC)->default(mPage::PAGE_TYPE_MALL);
        }
        $baseInfoForm->color('bgcolor', '活动页背景色')->hex();
        $baseInfoForm->tags('tags', '关联标签');
        $baseInfoForm->tags('relation_id', '关联活动');
        $baseInfoForm->datetimeRange('start_time', 'end_time', '活动时间');
        $baseInfoForm->imgUpload('cover_img_big', '活动页封面（大）');
        $baseInfoForm->imgUpload('cover_img_small', '活动页封面（小）');
        $baseInfoForm->imgUpload('icon', '活动封面小icon');
        $baseInfoForm->text('share_title', '分享标题');
        $baseInfoForm->text('share_desc', '分享描述');
        $baseInfoForm->imgUpload('share_img', '分享图片')->help('请上传32KB之内的分享图片');
        $baseInfoForm->action('/admin/activity/page/save/' . $id);
        return $baseInfoForm;
    }
}